package com.zhangye.test.cloud;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.codec.binary.Base64;
import org.asynchttpclient.AsyncCompletionHandler;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.Param;
import org.asynchttpclient.Response;
import org.json.JSONObject;

/**
 * Created by qinsi on 6/12/16.
 */
public class GetTarget {

	private static final String HOST       = "http://6296c09052012b394de6c002d7b81508.cn1.crs.easyar.com:8888";
    private static final String APP_KEY    = "a1d3c25006629cf8e3bbabd0c64003dd";
    private static final String APP_SECRET = "kYSRElAeH4ceubOnGnBiMqyrHYUgspVHZqBcibifXD10ldVjwhU1RGRwebMjGsry7ItPyreLGBQfG5ZB6IzSKspVmhOeLGQ3ZkB08G7BPE9gSnZyLQiscnHiEOiBS5I8";

    private static final String TARGET_ID  = "045b3359-bd79-473a-94e5-7ced52359845";

    private static List<Param> toParams(JSONObject jso) {
        return jso.keySet().stream()
                .map(key -> new Param(key, jso.getString(key)))
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        AsyncHttpClient client = new DefaultAsyncHttpClient();

        JSONObject params = new JSONObject();
        Auth.signParam(params, APP_KEY, APP_SECRET);

        client.prepareGet(HOST + "/target/" + TARGET_ID)
		.setHeader("Content-Type","application/json")
                .setQueryParams(toParams(params))
                .execute(new AsyncCompletionHandler<Void>() {
                    @Override
                    public Void onCompleted(Response response) throws Exception {
                        System.out.println(response.getResponseBody());
//                        Gson g = new Gson();
//                        EasyArResult er = g.fromJson(response.getResponseBody(), EasyArResult.class);
//                        System.out.println(decode(er.getResult().getTrackingImage().getBytes()));
                        client.close();
                        return null;
                    }
                });
    }
    public static byte[] decode(final byte[] bytes) {  
        return Base64.decodeBase64(bytes);  
    }  
	public static String encode(final byte[] bytes) {  
		return new String(Base64.encodeBase64(bytes));  
	}
}
